<template>
    <div>
        <Card :bordered="false" dis-hover class="ivu-mt">
            <Row :gutter="24" type="flex">
                <Col span="4">
                    <Input v-model="formData.keyword" placeholder="请输入患者姓名/手机号" element-id="name" clearable @on-enter="onLoads" @on-clear="onLoads"/>
                </Col>
                <Col span="3">
                    <Select v-model="formData.department_leader_id" placeholder="角色" clearable @on-change="onLoads">
                        <Option value="-1">普通员工</Option>
                        <Option value="2">项目管理员</Option>
                    </Select>
                </Col>
                <Col span="3">
                    <Select v-model="formData.project_id" placeholder="项目" clearable @on-change="onLoads">
                        <Option v-for="project in projectList" :key="project.id" :value="project.id">{{project.name}}</Option>
                    </Select>
                </Col>
                <Col span="2">
                    <Button type="primary" @click="handleAllocation()">新增</Button>
                </Col>
            </Row>
            <Table size="small" :loading="tableLoading" :columns="columns" :data="data" class="ivu-mt-16">
                <template slot-scope="{ row }" slot="status">
                    <Button v-if="row.status ==='1'" type="success" size="small" @click="changeStatus(row)">启用</Button>
                    <Button v-if="row.status ==='0'" type="error" size="small" @click="changeStatus(row)">停用</Button>
                </template>
                <template slot-scope="{ row }" slot="operation">
                    <a @click="handleAllocation(row)">编辑</a>
                </template>
            </Table>
            <div class="ivu-mt ivu-text-center">
                <Page
                        :total="total"
                        :current.sync="page"
                        show-total
                        show-elevator
                        :page-size="pageSize"
                        @on-change="changePage"
                        :page-size-opts="pageOpts"
                        show-sizer transfer
                        @on-page-size-change="changePageSize"
                />
            </div>
        </Card>
        <Modal
                v-model="modal"
                :title="edit ? '编辑' : '新增'"
                width="800"
                :mask-closable= "false"
                @on-cancel="handleDrawerCancel()">
            <Form :model="formItem" :label-width="80" :rules="ruleValidate" ref="formItem">
                <Row :gutter="12">
                    <Col span="12">
                        <FormItem label="姓名" prop="input">
                            <Input v-model="formItem.input" placeholder="请输入" clearable></Input>
                        </FormItem>
                    </Col>
                    <Col span="12">
                        <FormItem label="手机号" prop="phone">
                            <Input v-model="formItem.phone" placeholder="请输入" clearable></Input>
                        </FormItem>
                    </Col>
                    <Col span="12">
                        <FormItem label="项目" prop="project">
                            <Select v-model="formItem.project" multiple @on-change="changeproject">
                                <Option v-for="project in projectList" :key="project.id" :value="project.id">{{project.name}}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="12">
                        <FormItem label="帐号" prop="phone" clearable>
                            <Input disabled="disabled" v-model="formItem.phone" placeholder="手机号"></Input>
                        </FormItem>
                    </Col>
                    <Col span="12">
                        <FormItem label="密码" prop="password">
                            <Input v-model="formItem.password" type="password"  placeholder="请输入"></Input>
                        </FormItem>
                    </Col>
                    <Col span="12">
                        <FormItem label="确认密码" prop="confirm">
                            <Input v-model="formItem.confirm" type="password"  placeholder="请输入"></Input>
                        </FormItem>
                    </Col>
                    <Col span="12">
                        <FormItem label="状态" prop="switch">
                            <i-switch v-model="formItem.switch">
                                <span slot="open">On</span>
                                <span slot="close">Off</span>
                            </i-switch>
                        </FormItem>
                    </Col>
                    <Col span="12">
                        <FormItem label="是否为管理者" :label-width="120"  prop="isleader">
                            <i-switch v-model="formItem.isleader" :true-value="'2'" :false-value="'0'">
                                <span slot="open">Yes</span>
                                <span slot="close">No</span>
                            </i-switch>
                        </FormItem>
                    </Col>
                </Row>
            </Form>
            <div slot="footer">
                <Button @click="handleDrawerCancel()">取消</Button>
                <Button type="primary" :loading="loading" @click="handleSubmit('formItem')">确定</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
    import { GetMemberList, CreateMember, UpdateMember, UpdateMemberStatus, GetProjectSelectList } from '@api/setting'

    export default {
        name: 'diagnosis',
        data () {
            const validatePass = (rule, value, callback) => {
                if (value === '' && this.formItem.confirm === '') {
                    callback();
                } else {
                    if (this.formItem.confirm !== '') {
                        // 对第二个密码框单独验证
                        this.$refs.formItem.validateField('confirm');
                    }
                    callback();
                }
            };
            const validatePassCheck = (rule, value, callback) => {
                if (value === '' && this.formItem.password === '') {
                    callback();
                } else {
                    if (value !== this.formItem.password) {
                        callback(new Error('两次输入密码不一致!'));
                    } else {
                        callback();
                    }
                }
            };
            const validateProject = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请至少选择一个项目！'));
                } else {
                    callback();
                }
            };

            // model中手机验证规则方法
            const checkPhone = (rule, value, callback) => {
                const reg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
                if (value === '' || value === undefined || value === null) {
                    callback();
                } else if ((!reg.test(value)) && value !== '') {
                    callback(new Error('请输入正确的电话号码'));
                } else {
                    callback();
                }
            };

            return {
                modal: false,
                edit: false,
                loading: false,
                tableLoading: false,
                project_id: [],
                formData: {
                    keyword: '',
                    department_leader_id: '',
                    project_id: ''
                },
                formItem: {
                    input: '',
                    phone: '',
                    project: '',
                    password: '',
                    confirm: '',
                    switch: true,
                    isleader: '0'
                },
                ruleValidate: {
                    input: [
                        { required: true, message: '姓名不可为空', trigger: 'blur' }
                    ],
                    phone: [
                        { required: true, message: '手机号不可为空', trigger: 'blur' },
                        { validator: checkPhone, trigger: 'blur' }
                    ],
                    project: [
                        { validator: validateProject, trigger: 'blur' },
                        { validator: validateProject, trigger: 'change' }
                    ],
                    // 密码校验规则
                    password: [
                        { min: 6, max: 20, message: '长度在 6 到 20 个字母、符号或数字组合', trigger: 'blur' },
                        { validator: validatePass, trigger: 'blur' }
                    ],
                    confirm: [
                        { validator: validatePassCheck, trigger: 'blur' }
                    ]

                },
                columns: [
                    {
                        title: '名称',
                        key: 'name',
                        tooltip: true
                    },
                    {
                        title: '手机号',
                        key: 'mobile',
                        width: 130
                    },
                    {
                        title: '项目',
                        key: 'project',
                        tooltip: true
                    },
                    {
                        title: '部门',
                        key: 'department_name',
                        tooltip: true
                    },
                    {
                        title: '诊室',
                        key: 'clinic_name',
                        tooltip: true
                    },
                    {
                        title: '岗位',
                        key: 'profession_name',
                        tooltip: true
                    },
                    {
                        title: '机构角色',
                        key: 'department_leader',
                        tooltip: true
                    },
                    {
                        title: '最后登录时间',
                        key: 'last_time',
                        tooltip: true
                    },
                    {
                        title: '状态',
                        slot: 'status'
                    },
                    {
                        title: '操作',
                        slot: 'operation'
                    }
                ],
                data: [],
                // profession_list: [],
                // role_list: [],
                projectList: [],
                pageOpts: [10, 20, 30, 50],
                page: 1,
                pageSize: 10,
                total: 0
            }
        },
        created () {
            this.onLoad();
            this.getProjectList();
        },
        methods: {
            onLoads() {
                this.page = 1
                this.onLoad()
            },
            onLoad () {
                /**
                 * @description 员工列表
                 * @param {Object} param page  {String} 页数
                 * @param {Object} param pageSize {String} 条数/页
                 */
                this.tableLoading = true
                const params = this.getParam()
                GetMemberList(params).then((res) => {
                    // if (this.profession_list.length === 0) {
                    //     this.profession_list = res.profession_list
                    // }
                    // if (this.role_list.length === 0) {
                    //     this.role_list = res.role_list
                    // }
                    this.data = res.list
                    this.page = res.page
                    this.pageSize = res.pageSize
                    this.total = res.total
                }).finally(() => {
                    this.tableLoading = false
                })
            },
            getParam () {
                let params = {
                    page: this.page,
                    pageSize: this.pageSize,
                    // profession_id:  this.formData.profession_id,
                    department_leader_id: this.formData.department_leader_id,
                    keyword: this.formData.keyword,
                    project_id: this.formData.project_id
                }
                return params;
            },

            /* *** 注释信息 @author Zhou @date 2020/2/14 *** */
            /* 获取项目列表（新增编辑使用）
          /* ******************************************** */
            getProjectList () {
                GetProjectSelectList().then((res) => {
                    this.projectList = res.list
                }).catch((err) => {
                    // console.log(err)
                })
            },

            changePage (page) {
                this.page = page;
                this.onLoad();
            },
            changePageSize (pagesize) {
                this.pageSize = pagesize;
                this.onLoad();
            },
            handleAllocation (row) {
                this.modal = true;
                if (row) {
                    this.edit = true;
                    this.project_id = row.project_id ? row.project_id.split(',') : '',
                    this.formItem = {
                        id: row.id,
                        input: row.name,
                        phone: row.mobile,
                        project: row.project_id ? row.project_id.split(',') : '',
                        switch: row.status === '1',
                        isleader: row.is_department_leader
                    }
                }
            },
            changeproject() {
                let bool = false
                for (let item of this.project_id) {
                    if (!bool) {
                        if (this.formItem.project.indexOf(item)<0) {
                            bool = true
                        }
                    }
                }
                if (bool) {
                    this.$Modal.confirm({
                        title: '更换项目',
                        content: '确定删除项目后，患者清空，释放到公海',
                        onOk: () => {},
                        onCancel: () => {
                        this.formItem.project = this.project_id
                        }
                    });
                }
            },
            handleDrawerCancel () {
                this.modal = false;
                this.edit = false;
                this.project_id = []
                this.formItem = {
                    input: '',
                    phone: '',
                    project: '',
                    password: '',
                    confirm: '',
                    switch: true,
                    isleader: '0'
                };
                this.$refs['formItem'].resetFields()
            },
            handleSubmit (name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        this.loading = true;
                        const params = {
                            name: this.formItem.input,
                            status: this.formItem.switch ? '1' : '0',
                            mobile: this.formItem.phone,
                            project_id: (this.formItem.project).join(','),
                            user_name: this.formItem.phone,
                            password: this.formItem.password,
                            password_re: this.formItem.confirm,
                            is_department_leader: this.formItem.isleader
                        }
                        if (this.edit) {
                            params.id = this.formItem.id;
                            this.updateSubmit(params);
                        } else {
                            this.createSubmit(params);
                        }
                    } else {
                        console.log('表单校验失败！')
                    }
                })
            },
            changeStatus (row) {
                const param = {
                    id: row.id,
                    status: row.status === '1' ? '0' : '1'
                }
                this.$Modal.confirm({
                    title: '切换员工状态',
                    content: '确定' + (row.status === '1' ? '停用 ' : '启用 ') + row.name,
                    onOk: () => {
                        this.changeSubmit(param);
                    }
                });
            },

            createSubmit (params) {
                CreateMember(params).then((res) => {
                    this.$Message.success('创建成功');
                    this.loading = false;
                    this.onLoad();
                    this.handleDrawerCancel();
                }).catch(() => {
                    this.loading = false;
                })
            },
            updateSubmit (params) {
                UpdateMember(params).then((res) => {
                    this.$Message.success('修改成功');
                    this.loading = false;
                    this.onLoad();
                    this.handleDrawerCancel();
                }).catch(() => {
                    this.loading = false;
                })
            },
            changeSubmit (params) {
                UpdateMemberStatus(params).then((res) => {
                    this.$Message.success('状态切换成功');
                    this.onLoad();
                }).catch(() => {})
            }

        }
    }
</script>

<style scoped>
</style>
